package com.woniuxy.auth.service.impl;

import com.woniuxy.auth.dao.RbacManagerDao;
import com.woniuxy.auth.dao.RbacMenuDao;
import com.woniuxy.auth.service.MenuService;
import com.woniuxy.commons.entity.auth.dto.RbacManagerDto;
import com.woniuxy.commons.entity.auth.dto.RbacMenuDto;
import com.woniuxy.commons.result.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.soap.SAAJMetaFactory;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO:
 * <P> Date: 2022/4/28:9:54
 * <P> Description:
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private RbacMenuDao menuDao;


    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public Result hasPerms(String refreshToken, String perms) {

        RbacManagerDto rbacManagerDto =
                (RbacManagerDto) redisTemplate.opsForHash().get(refreshToken, "roles");

        //如果获取当前用户的权限不存在 说明可能是第一次查询
        if (rbacManagerDto == null) {

            // 尝试获取存入的map数组 如果为空 说明token不存在 用户没登录
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(refreshToken);

            String uname = "uname";


            // 如果不存在这个key 那么token没在redis里面 直接返回
            if (!entries.containsKey(uname)) {
                return Result.fail().message("没有权限");
            }

            // 如果存在 获得对应的账户名 查询权限并存入到redis
            uname = (String) entries.get("uname");

            //获得当前账号的所有权限
            List<RbacMenuDto> rbacMenuDtoList = menuDao.findMenuByManagerUname(uname);

            //遍历存入对应的RbacManagerDto 和 RbacMenuDto


            rbacManagerDto = new RbacManagerDto();
            rbacManagerDto.setAccount(uname);


            rbacMenuDtoList.forEach(rbacManagerDto::addOrganizationComponent);
            redisTemplate.opsForHash().put(refreshToken, "roles", rbacManagerDto);
        }


        boolean has = rbacManagerDto.isHas(perms);

        if (has) {
            return Result.ok().message("拥有权限");
        }
        return Result.fail().message("没有权限");


    }
}
